from django.utils.deprecation import MiddlewareMixin
from web import models
from django.shortcuts import redirect
# from django.conf import settings
from s28 import settings
import datetime
from scripts.init_price_police import S28

#  千万要记住要注册中间件
class AuthMiddleware(MiddlewareMixin):
    def process_request(self, request):
        """如果用户登陆 则request中赋值"""
        user_id = request.session.get('user_id', 0)  # 这个可以拿到用户的id
        request.user_id = user_id
        user_name = models.BOOK().search_id('id', str(user_id))
        request.user_name = models.BOOK().search_to_id('id', str(user_name))  # 拿到了用户的名字
        res_user_name = models.BOOK().search_to_id('id', str(user_name))
        request.tracer = res_user_name
        if request.tracer == True:
            request.tracer = False
        """
        1.获取当前用户访问的rul
        2.检查url是否在白名单中，如果在则可以继续向后访问，如果不在则进行判断是否已登录
        """
        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            return
        if not request.tracer:
            return redirect('login')

        """
        登录成功后 访问后台管理 获取当前用户的额度
        """
        print(user_id,'我这个人的id')
        user_vip_tuple = S28().search('user_as_vip', {'user_id': user_id})
        print('我这个人的额度',user_vip_tuple)
        this_user_as_vip = user_vip_tuple[len(user_vip_tuple) - 1][3]
        vip = S28().search('vip', {'id': this_user_as_vip})


        request.vip_name = vip[0][2]
        request.project_num = vip[0][4]
        request.people_num = vip[0][5]
        request.space_num = vip[0][6]
        request.one_space_num = vip[0][7]


    def process_view(self, request, view, args, kwargs):
        # 判断是否已经进入了项目
        if not request.path_info.startswith('/manage/'):
            #print(request.path_info, 'start_with!!!')
            return

        project_id = kwargs.get('project_id')
        # 是否是我创建的项目
        project_object = S28().py_searche('select * from project where id="{0}" and creator_id="{1}"'.format(project_id, request.user_id))
        if len(project_object) != 0:
            #request.tracer.project = project_object
            request.obj = project_object
            #print('中间件', request.obj)
            return
        # 是否是我参与的项目
        project_user_object = S28().py_searche('select * from invitation where project_id="{0}" and user_information_id="{1}"'.format(project_id, request.user_id))
        if len(project_user_object) != 0:
            request.obj = S28().py_searche('select * from project where id="{}"'.format(project_user_object[0][1]))
            return

        # 既不是我创建的 也不是我参与的
        return redirect('project_list')
